import React, { useState } from "react";
import Link from "next/link";
import { FormComponentProps } from "antd/es/form";
import { Form, Input, Button } from "antd";

import style from "./index.module.scss";
import { UserApi } from "@/api/user";
import { saveUser, setToken } from "@/utils/catch";
import Router from "next/router";

// 继承自 antd Form组件
interface ILoginProps extends FormComponentProps {}

const Login: React.FC<ILoginProps> = ({ form }) => {
  const { getFieldDecorator } = form;
  const [loading, setLoading] = useState(false);
  const submit = e => {
    e.preventDefault();
    form.validateFields(async (err, values) => {
      if (!err) {
        setLoading(true);
        try {
          const userInfo = await UserApi.login(values);
          saveUser(userInfo);
          setToken(userInfo.token);
          Router.push("/");
        } catch (error) {
          setLoading(false);
        }
      }
    });
  };
  return (
    <div className={style.wrapper}>
      <div className={style.container}>
        <Form onSubmit={submit}>
          <Form.Item label="用户名">
            {getFieldDecorator("name", {
              rules: [{ required: true, message: "请输入用户名" }]
            })(<Input />)}
          </Form.Item>
          <Form.Item label="密码">
            {getFieldDecorator("password", {
              rules: [{ required: true, message: "请输入密码" }]
            })(<Input type="password" />)}
          </Form.Item>
          <Form.Item>
            <Button
              type="primary"
              loading={loading}
              style={{ width: "100%" }}
              htmlType="submit"
            >
              登录
            </Button>
            <Link href="/register">
              <a>去注册</a>
            </Link>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};

export default Form.create<ILoginProps>({ name: "login" })(Login);
